// pages/login/login.js
import { PHONE} from '../../utils/util.js'
import { request} from '../../utils/network.js'
var app = getApp()
var globalData = app.globalData
Page({

  /**
   * 页面的初始数据
   */
  data: {
    username: '',
    password: '',
    err: {  // 登录信息错误时显示
      errStatus: false,
      errText: ''
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
  },

  /**
   * 输入账号和密码
   */
  userInput:function (e) {
    let username = e.detail.value
    this.setData({
      err: {
        errStatus: false,
        errText: ''
      },
      username: e.detail.value
    })
    // if (PHONE.test(username)) {
    //   this.setData({
    //     err: {
    //       errStatus: false,
    //       errText: ''
    //     },
    //     username: e.detail.value
    //   })
    // } else {
    //   console.log('错误')
    //   this.setData({
    //     err:{
    //       errStatus: true,
    //       errText: '账号格式错误'
    //     } 
    //   })
    // }
  },
  passwordInput: function (e) {
    this.setData({
      password: e.detail.value
    })
  },
  loginAction: function () {
    var that = this;
    let data = {
      code: globalData.code,
      username: that.data.username,
      password: that.data.password
    }
    if (that.data.username === '') {
      that.setData({
        err: {
          errStatus: true,
          errText: '用户名不能为空'
        }
      })
      return false;
    } 
    if (that.data.password === '') {
      that.setData({
        err: {
          errStatus: true,
          errText: '密码不能为空'
        }
      })
      return false;
    } 
    request (
      '/distributor/login',
      data,
      function success (res){
        console.log(res)
        if (res.resultCode === 2000) {
          globalData.receiverInfo = res.data
          wx.setStorage({
            key: 'token',
            data: res.data.token,
          })
          wx.showToast({
            title: '登录成功',
            icon: 'success',
            success: ()=>{
              wx.switchTab({
                url:'/pages/store/store'
              })
            }
          })
        } else {
          wx.showToast({
            title: '请求出错了',
            icon: 'none',
          })
        }
      }, 
      function fail(){
        wx.showToast({
          title: '请求错误',
          icon: 'none',
        })
      }
    )
  }
})